package com.cloudcentral.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudcentral.entity.Platform;
import com.cloudcentral.entity.dto.EnableDTO;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.feign.ToolkitFeign;
import com.cloudcentral.mapper.PlatformBaseMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 系统平台表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2023-10-27
 */
@Service
public class PlatformService extends ServiceImpl<PlatformBaseMapper, Platform> {
  private final ToolkitFeign toolkitFeign;

  @Autowired
  public PlatformService(ToolkitFeign toolkitFeign) {
    this.toolkitFeign = toolkitFeign;
  }

  public Platform getByName(String name) {
    return baseMapper.getByName(name);
  }

  public Platform getByCode(String code) {
    return baseMapper.getByCode(code);
  }

  public Platform getByURI(String uri) {
    return baseMapper.getByURI(uri);
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean enable(EnableDTO dto) throws FailureException {
    if (dto.getId() == null) throw new FailureException("缺少ID");
    else if (dto.getEnable() == null) throw new FailureException("缺少启用状态");
    else {
      UpdateWrapper<Platform> updateWrapper = new UpdateWrapper<>();
      updateWrapper.set("enable", dto.getEnable() ? 1 : 0).eq("id", dto.getId());
      return update(updateWrapper);
    }
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Platform submit(Platform platform) throws Exception {
    if (StringUtils.isBlank(platform.getName())) throw new FailureException("缺少名称");
    else if (StringUtils.isBlank(platform.getCode())) throw new FailureException("缺少代码");
    else if (StringUtils.isBlank(platform.getUri())) throw new FailureException("缺少链接");
    else {
      saveOrUpdate(platform);
      return getById(platform.getId());
    }
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean delete(Long id) throws Exception {
    Platform platform = getById(id);
    removeById(id);
    toolkitFeign.delete(platform.getIcon());
    toolkitFeign.delete(platform.getCover());
    return true;
  }
}
